package io.elegant.widgets

import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import com.google.protobuf.Any
import io.elegant.sessions.BaseSession
import io.elegant.toAny
import io.elegant.toBoolValue
import kotlinx.coroutines.CoroutineScope

class CheckBoxWidget<T: View>(
    private val session: BaseSession,
    group: ViewGroup,
    cs: CoroutineScope
): BaseTextWidget<T>(session, group, cs) {
    override fun onReceive(name: String, sessionId: Long, futureId: Long, vararg argv: Any): Boolean {
        if (when (name) {
                "isChecked" -> isChecked(sessionId, futureId)
                "setChecked" -> setChecked(*argv)
                else -> null
        } == null)
            return super.onReceive(name, sessionId, futureId, *argv)
        return true
    }
    private fun isChecked(sessionId: Long, futureId: Long) {
        val checked = (view as CheckBox?)?.isChecked ?: false
        onIsChecked(checked.toAny(), sessionId, futureId)
    }
    private fun onIsChecked(checked: Any, sessionId: Long, futureId: Long) = session.apply {
        sendAction("onIsChecked", sessionId, futureId, checked)
    }
    private fun setChecked(vararg argv: Any) {
        (view as CheckBox?)?.isChecked = argv[0].toBoolValue()
    }
}